import 'package:flutter/material.dart';

import '../../core/app_config.dart';
import '../../core/gitcode_api.dart';
import '../repository_list_page.dart';
import '../user_list_page.dart';
import '../user_detail_page.dart';
import '../repository_detail_page.dart';
import '../../widgets/repository_card.dart';
import '../../widgets/user_card.dart';

/// 区分搜索模式：用户 或 仓库。
enum QueryMode { user, repository }

/// 搜索页面（Git口袋中心）
/// 提供用户和仓库的搜索功能
class SearchPage extends StatefulWidget {
  const SearchPage({super.key});

  @override
  State<SearchPage> createState() => _SearchPageState();
}

class _SearchPageState extends State<SearchPage> {
  _SearchPageState() {
    _tokenController.text = AppConfig.demoToken;
  }

  /// 输入框控制器、表单 key、API 客户端等 UI 层状态。
  final _keywordController = TextEditingController();
  final _tokenController = TextEditingController();
  final _formKey = GlobalKey<FormState>();
  final _client = GitCodeApiClient();

  QueryMode _mode = QueryMode.user;
  List<GitCodeSearchUser> _userResults = const [];
  List<GitCodeRepository> _repoResults = const [];
  String? _errorMessage;
  bool _isLoading = false;
  bool _obscureToken = true;

  @override
  void dispose() {
    _keywordController.dispose();
    _tokenController.dispose();
    super.dispose();
  }

  /// 统一的搜索入口：根据模式调用不同接口，并处理通用的 Loading / Error 逻辑。
  Future<void> _performSearch() async {
    if (_isLoading) return;
    if (!_formKey.currentState!.validate()) return;

    FocusScope.of(context).unfocus();

    setState(() {
      _isLoading = true;
      _errorMessage = null;
      _userResults = const [];
      _repoResults = const [];
    });

    final token = _tokenController.text.trim();

    try {
      // 根据当前模式执行对应的 API 请求。
      if (_mode == QueryMode.user) {
        final users = await _client.searchUsers(
          keyword: _keywordController.text,
          personalToken: token,
          perPage: 8,
        );
        setState(() {
          _userResults = users;
        });
      } else {
        final repos = await _client.searchRepositories(
          keyword: _keywordController.text,
          personalToken: token,
          perPage: 8,
        );
        setState(() {
          _repoResults = repos;
        });
      }
    } on GitCodeApiException catch (error) {
      setState(() {
        _errorMessage = error.message;
      });
    } catch (error) {
      setState(() {
        _errorMessage = '未知错误：$error';
      });
    } finally {
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('GitCode 搜索中心'),
        elevation: 0,
      ),
      body: SafeArea(
        child: SingleChildScrollView(
          padding: const EdgeInsets.all(20),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              _buildIntro(context),
              const SizedBox(height: 20),
              _buildFormCard(),
              const SizedBox(height: 20),
              _buildResultSection(),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildIntro(BuildContext context) {
    final theme = Theme.of(context);
    return Text(
      '输入关键字 + access token，立即查询 GitCode 用户或仓库（搜索接口需授权）。',
      style: theme.textTheme.bodyMedium?.copyWith(fontWeight: FontWeight.w600),
    );
  }

  Widget _buildFormCard() {
    return Card(
      elevation: 0,
      clipBehavior: Clip.antiAlias,
      child: Padding(
        padding: const EdgeInsets.all(20),
        child: Form(
          key: _formKey,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              _buildModeSwitcher(),
              const SizedBox(height: 12),
              TextFormField(
                controller: _keywordController,
                textInputAction: TextInputAction.search,
                decoration: const InputDecoration(
                  labelText: '搜索关键字',
                  hintText: '例如：iflytek / spark',
                  prefixIcon: Icon(Icons.search),
                ),
                validator: (value) {
                  if (value == null || value.trim().isEmpty) {
                    return '请输入关键字';
                  }
                  return null;
                },
                onFieldSubmitted: (_) => _performSearch(),
              ),
              const SizedBox(height: 12),
              TextFormField(
                controller: _tokenController,
                decoration: InputDecoration(
                  labelText: 'Access Token',
                  hintText: 'GitCode 个人设置 > Access Token',
                  prefixIcon: const Icon(Icons.vpn_key_outlined),
                  suffixIcon: IconButton(
                    icon: Icon(
                      _obscureToken
                          ? Icons.visibility_off_outlined
                          : Icons.visibility_outlined,
                    ),
                    onPressed: () {
                      setState(() {
                        _obscureToken = !_obscureToken;
                      });
                    },
                  ),
                ),
                obscureText: _obscureToken,
                validator: (value) {
                  if (value == null || value.trim().isEmpty) {
                    return '搜索接口需提供 access token';
                  }
                  return null;
                },
              ),
              const SizedBox(height: 16),
              FilledButton.icon(
                onPressed: _isLoading ? null : _performSearch,
                icon: _isLoading
                    ? const SizedBox(
                        width: 18,
                        height: 18,
                        child: CircularProgressIndicator(strokeWidth: 2),
                      )
                    : const Icon(Icons.play_arrow_rounded),
                label: Text(_isLoading ? '查询中...' : '查询'),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildResultSection() {
    if (_isLoading) {
      return const Center(child: CircularProgressIndicator());
    }

    if (_errorMessage != null) {
      final scheme = Theme.of(context).colorScheme;
      return _InfoBanner(
        icon: Icons.error_outline,
        background: scheme.errorContainer,
        textColor: scheme.onErrorContainer,
        message: _errorMessage!,
      );
    }

    if (_mode == QueryMode.user) {
      return _buildUserResults();
    }
    return _buildRepositoryResults();
  }

  Widget _buildModeSwitcher() {
    return SegmentedButton<QueryMode>(
      segments: const [
        ButtonSegment(
          value: QueryMode.user,
          icon: Icon(Icons.person_outline),
          label: Text('用户'),
        ),
        ButtonSegment(
          value: QueryMode.repository,
          icon: Icon(Icons.bookmark_outline),
          label: Text('仓库'),
        ),
      ],
      selected: <QueryMode>{_mode},
      onSelectionChanged: (selection) {
        final next = selection.first;
        if (next != _mode) {
          // 切换模式时及时清理旧结果，避免跨模式串数据。
          setState(() {
            _mode = next;
            _errorMessage = null;
            _userResults = const [];
            _repoResults = const [];
          });
        }
      },
    );
  }

  Widget _buildUserResults() {
    if (_userResults.isEmpty) {
      final scheme = Theme.of(context).colorScheme;
      return _InfoBanner(
        icon: Icons.info_outline,
        background: scheme.primaryContainer,
        textColor: scheme.onPrimaryContainer,
        message: '暂无数据，输入关键字并点击"查询"试试。',
      );
    }

    return Column(
      children: [
        // 使用新的自定义用户卡片组件
        ..._userResults.map(
          (user) => UserCard(
            user: user,
            onTap: () {
              Navigator.of(context).push(
                MaterialPageRoute(
                  builder: (context) => UserDetailPage(
                    username: user.login,
                    token: _tokenController.text.trim().isNotEmpty
                        ? _tokenController.text.trim()
                        : null,
                  ),
                ),
              );
            },
          ),
        ),
        const SizedBox(height: 16),
        // 添加查看全部按钮，跳转到带分页的用户列表页
        FilledButton.icon(
          onPressed: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => UserListPage(
                  keyword: _keywordController.text,
                  token: _tokenController.text.trim(),
                ),
              ),
            );
          },
          icon: const Icon(Icons.list),
          label: const Text('查看全部并加载更多'),
        ),
      ],
    );
  }

  Widget _buildRepositoryResults() {
    if (_repoResults.isEmpty) {
      final scheme = Theme.of(context).colorScheme;
      return _InfoBanner(
        icon: Icons.info_outline,
        background: scheme.secondaryContainer,
        textColor: scheme.onSecondaryContainer,
        message: '还没有结果，输入关键字并点击查询即可获取仓库列表。',
      );
    }

    return Column(
      children: [
        // 使用新的自定义仓库卡片组件
        ..._repoResults.map(
          (repo) => RepositoryCard(
            repository: repo,
            onTap: () {
              // 从 fullName 解析 owner 和 repo
              final fullName = repo.fullName;
              final parts = fullName.split('/');
              if (parts.length >= 2) {
                final owner = parts[0];
                final repoName = parts.sublist(1).join('/');
                Navigator.of(context).push(
                  MaterialPageRoute(
                    builder: (context) => RepositoryDetailPage(
                      owner: owner,
                      repo: repoName,
                      token: _tokenController.text.trim().isNotEmpty
                          ? _tokenController.text.trim()
                          : null,
                      projectId: repo.projectId,
                    ),
                  ),
                );
              } else {
                // 如果无法解析，使用 ownerLogin 作为 fallback
                final owner = repo.ownerLogin ?? parts[0];
                final repoName = parts.length > 1 ? parts[1] : parts[0];
                Navigator.of(context).push(
                  MaterialPageRoute(
                    builder: (context) => RepositoryDetailPage(
                      owner: owner,
                      repo: repoName,
                      token: _tokenController.text.trim().isNotEmpty
                          ? _tokenController.text.trim()
                          : null,
                      projectId: repo.projectId,
                    ),
                  ),
                );
              }
            },
          ),
        ),
        const SizedBox(height: 16),
        // 添加查看全部按钮，跳转到带分页的列表页
        FilledButton.icon(
          onPressed: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => RepositoryListPage(
                  keyword: _keywordController.text,
                  token: _tokenController.text.trim(),
                ),
              ),
            );
          },
          icon: const Icon(Icons.list),
          label: const Text('查看全部并加载更多'),
        ),
      ],
    );
  }
}

class _InfoBanner extends StatelessWidget {
  const _InfoBanner({
    required this.icon,
    required this.background,
    required this.textColor,
    required this.message,
  });

  final IconData icon;
  final Color background;
  final Color textColor;
  final String message;

  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: background,
        borderRadius: BorderRadius.circular(12),
      ),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Icon(icon, color: textColor),
          const SizedBox(width: 12),
          Expanded(
            child: Text(
              message,
              style: Theme.of(context)
                  .textTheme
                  .bodyMedium
                  ?.copyWith(color: textColor),
            ),
          ),
        ],
      ),
    );
  }
}

